﻿//using Facebook;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.IO;
using System.Threading;
using System.Windows.Forms;

namespace FaceBookApp
{
    public enum IslemCinsleri
    {
        Bos,
        GirisYap,
        CikisYap,
        Post
    }

    public partial class frmMain : Form
    {
        DataTable hesaplar = new DataTable();
        IslemCinsleri currentProcess = IslemCinsleri.Bos;
        public string Token { get; set; }

        public frmMain()
        {
            InitializeComponent();
            hesaplar.Columns.Add("MailAdresi", typeof(string));
            hesaplar.Columns.Add("Sifresi", typeof(string));
            hesaplar.Columns.Add("Durum", typeof(string));

            webBrowser1.ScriptErrorsSuppressed = true;
            //webBrowser1.Navigated += webBrowser1_Navigated;
        }

        void webBrowser1_Navigated(object sender, WebBrowserNavigatedEventArgs e)
        {
            //var fb = new FacebookClient();
            //FacebookOAuthResult oauthResult;
            //if (!fb.TryParseOAuthCallbackUrl(e.Url, out oauthResult))
            //    return;
            //if (oauthResult.IsSuccess)
            //    LoginSucceeded(oauthResult);
            //else
            //    MessageBox.Show("Login fail");
        }

        private void frmMain_Load(object sender, EventArgs e)
        {
            dataGridView1.DataSource = hesaplar;
            if (File.Exists(Application.StartupPath + "\\hesaplar.ini"))
            {
                using (StreamReader sr = new StreamReader(Application.StartupPath + "\\hesaplar.ini"))
                {
                    while (sr.Peek() > -1)
                    {
                        string[] fields = sr.ReadLine().Split(';');
                        hesaplar.Rows.Add(fields);
                    }
                    sr.Close();
                }
            }
            cmbTablolar.Items.AddRange(Database.TabloAdlari());
            if (cmbTablolar.Items.Count > 0)
            {
                cmbTablolar.SelectedIndex = 0;
            }
        }


        private void btnLogin_Click(object sender, EventArgs e)
        {
            if (webBrowser1.Document != null)
            {
                currentProcess = IslemCinsleri.CikisYap;
                var theElementCollection = webBrowser1.Document.GetElementsByTagName("input");
                foreach (HtmlElement curElement in theElementCollection)
                {
                    if (curElement.OuterHtml.IndexOf("Çıkış") > -1)
                    {
                        curElement.InvokeMember("click");
                    }
                }
            }

            currentProcess = IslemCinsleri.GirisYap;
            webBrowser1.Navigate("https://login.facebook.com/login.php?login_attempt=1");
            webBrowser1.DocumentCompleted += webBrowser1_DocumentCompleted;

        }

        void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
            if (currentProcess == IslemCinsleri.GirisYap)
            {
                if (dataGridView1.CurrentRow != null)
                {
                    HtmlElement ele = webBrowser1.Document.GetElementById("email");
                    if (ele != null)
                        ele.InnerText = dataGridView1[0, dataGridView1.CurrentRow.Index].Value.ToString();

                    ele = webBrowser1.Document.GetElementById("pass");
                    if (ele != null)
                        ele.InnerText = dataGridView1[1, dataGridView1.CurrentRow.Index].Value.ToString();

                    ele = webBrowser1.Document.GetElementById("Login");
                    if (ele != null)
                        ele.InvokeMember("click");
                }
            }
        }

        private string GetComposerID()
        {
            string value = "";
            if (webBrowser1.Document != null)
            {
                HtmlElementCollection elementsByTagName = this.webBrowser1.Document.GetElementsByTagName("input");
                IEnumerator enumerator2 = elementsByTagName.GetEnumerator();
                while (enumerator2.MoveNext())
                {
                    HtmlElement htmlElement2 = (HtmlElement)enumerator2.Current;
                    if (htmlElement2.GetAttribute("name").Equals("xhpc_composerid"))
                    {
                        value = htmlElement2.GetAttribute("value");
                        break;
                    }
                }
            }
            return value;
        }

        private void yeniGonder(string sayfaid)
        {
            if (webBrowser1.Document != null)
            {
                HtmlElementCollection elementsByTagName = this.webBrowser1.Document.GetElementsByTagName("input");
                IEnumerator enumerator2 = elementsByTagName.GetEnumerator();
                while (enumerator2.MoveNext())
                {
                    HtmlElement htmlElement2 = (HtmlElement)enumerator2.Current;
                    if (htmlElement2.GetAttribute("name").Equals("xhpc_composerid"))
                    {
                        htmlElement2.SetAttribute("value", this.kodver(1));
                    }
                    if (htmlElement2.GetAttribute("name").Equals("xhpc_targetid"))
                    {
                        htmlElement2.SetAttribute("value", sayfaid);
                    }
                    if (htmlElement2.GetAttribute("name").Equals("xhpc_timeline"))
                    {
                        htmlElement2.SetAttribute("value", "0");
                    }
                }
            }
        }

        private void SetPageID(string pageID)
        {
            if (webBrowser1.Document != null)
            {
                HtmlElementCollection elementsByTagName = this.webBrowser1.Document.GetElementsByTagName("input");
                IEnumerator enumerator2 = elementsByTagName.GetEnumerator();
                while (enumerator2.MoveNext())
                {
                    HtmlElement htmlElement2 = (HtmlElement)enumerator2.Current;
                    if (htmlElement2.GetAttribute("name").Equals("xhpc_targetid"))
                    {
                        htmlElement2.SetAttribute("value", pageID);
                        break;
                    }
                }
            }
        }

        private void divChange(string value)
        {
            if (webBrowser1.Document != null)
            {
                HtmlElementCollection elementsByTagName3 = this.webBrowser1.Document.GetElementsByTagName("div");
                IEnumerator enumerator3 = elementsByTagName3.GetEnumerator();
                while (enumerator3.MoveNext())
                {
                    HtmlElement htmlElement3 = (HtmlElement)enumerator3.Current;
                    if (htmlElement3.GetAttribute("id").Equals(value))
                    {
                        string kod = this.kodver(1);
                        htmlElement3.SetAttribute("id", kod);
                    }
                }
            }
        }

        private void PaylasClick()
        {
            if (webBrowser1.Document != null)
            {
                HtmlElementCollection elementsByTagName = this.webBrowser1.Document.GetElementsByTagName("input");
                IEnumerator enumerator = elementsByTagName.GetEnumerator();
                while (enumerator.MoveNext())
                {
                    HtmlElement htmlElement = (HtmlElement)enumerator.Current;
                    if (htmlElement.GetAttribute("value").Equals("Paylaş"))
                    {
                        htmlElement.InvokeMember("click");
                        break;
                    }
                }
            }
        }

        private string kodver(object data)
        {
            int num = 1000000;
            int num2 = 9999999;
            Random rnd = new Random();
            int num3 = checked(num2 - num + 1);
            float num4 = (float)num3 * rnd.Next();
            num4 += (float)num;
            data = (int)num4;
            return data.ToString();
        }

        private void btnHazirla_Click(object sender, EventArgs e)
        {
            if (webBrowser1.Document != null)
            {
                string compID = GetComposerID();
                divChange(compID);
                btnHazirla.Enabled = false;
                btnBaslat.Enabled = true;
                btnDurdur.Enabled = true;
            }
            else
            {
                MessageBox.Show("Giriş yapınız !");
            }
        }

        private void btnGonder_Click(object sender, EventArgs e)
        {

        }

        //public void LoginSucceeded(FacebookOAuthResult oauthResult)
        //{
        //    var token = FbHelpers.GetAccessToken(oauthResult);
        //    Token = token;
        //    dynamic user = FbHelpers.GetUser(token);
        //}

        public void Login()
        {
            //var loginUrl = FbHelpers.GetLoginUrl();
            //webBrowser1.Navigate(loginUrl);
        }

        private void button1_Click(object sender, EventArgs e)
        {
            Login();
        }

        private void btnPostVideo_Click(object sender, EventArgs e)
        {
            //if (comboBox1.SelectedIndex == 0)
            //{
            //    FbHelpers.Post(Token, txtPost.Text);
            //}
            //else
            //{
            //    FbHelpers.Post(Database.NextPage(cmbTablolar.Text), Token, txtPost.Text);
            //}
        }

        private void btnAra_Click(object sender, EventArgs e)
        {
            //var rs = FbHelpers.SearchPage(txtPost.Text, Token);
        }

        private void btnResimGonder_Click(object sender, EventArgs e)
        {
            OpenFileDialog dlg = new OpenFileDialog();
            dlg.Filter = "";
            dlg.InitialDirectory = "";
            if (dlg.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                if (comboBox1.SelectedIndex == 0)
                {
                    //FbHelpers.PostWithPhoto(Token, txtPost.Text, dlg.FileName);
                }
                else
                {
                    //FbHelpers.PostWithPhoto(Database.NextPage(cmbTablolar.Text), Token, txtPost.Text, dlg.FileName);
                }
            }
        }
        private void frmMain_FormClosing(object sender, FormClosingEventArgs e)
        {
            using (StreamWriter sw = new StreamWriter(Application.StartupPath + "\\hesaplar.ini", false))
            {
                for (int i = 0; i < hesaplar.Rows.Count; i++)
                {
                    sw.WriteLine(hesaplar.Rows[i][0].ToString() + ";" + hesaplar.Rows[i][1].ToString() + ";" + hesaplar.Rows[i][2].ToString());
                }
                sw.Close();
            }
            System.Environment.Exit(System.Environment.ExitCode);
            Application.Exit();
        }

        private void btnBaslat_Click(object sender, EventArgs e)
        {
            timer1.Interval = Convert.ToInt32(textBox1.Text) * 1000;
            timer1.Enabled = true;
        }

        private void btnDurdur_Click(object sender, EventArgs e)
        {
            timer1.Enabled = false;
            sayac = 999;
            PencereKapat();
        }

        int sayac = 0;
        private void PencereKapat()
        {
            try
            {
                if (!string.IsNullOrEmpty(txtPencereSay.Text))
                {
                    int limit = Convert.ToInt32(txtPencereSay.Text);
                    if (limit > 0 && sayac > limit)
                    {
                        foreach (Process item in Process.GetProcesses())
                        {
                            if (item.ProcessName == "iexplore")
                            {
                                item.Kill();
                            }
                        }
                        sayac = 0;
                    }
                }
            }
            catch (Exception)
            {
            }
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            if (webBrowser1.Document != null)
            {
                string pageid = Database.NextPage(cmbTablolar.Text);
                //SetPageID(pageid);
                yeniGonder(pageid);
                PaylasClick();
                lblGonderimSayisi.Text = (Convert.ToInt32(lblGonderimSayisi.Text) + 1).ToString();
                listBox1.Items.Add("http://www.facebook.com/" + pageid);
                sayac++;
                PencereKapat();
            }
        }

        private void topluSayfaEklemeToolStripMenuItem_Click(object sender, EventArgs e)
        {
            frmSayfaEkle frm = new frmSayfaEkle();
            frm.ShowDialog(this);
        }

        private void button2_Click(object sender, EventArgs e)
        {
            webBrowser1.Navigate(txtSayfa.Text);

        }

        private void listBox1_Click(object sender, EventArgs e)
        {
            if (listBox1.SelectedIndex > -1)
            {
                Process.Start(listBox1.SelectedItem.ToString());
            }
        }
    }
}
